﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Outcoder. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2013-04-19 12:02:41Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

using Windows.Storage;
using Windows.System.Threading;

using Outcoder.Concurrency;

using DiagnosticsDebug = System.Diagnostics.Debug;

namespace Outcoder.Logging.Loggers
{
	public class LocalStorageLog : LogBase
	{
		bool writeToConsoleAsWell = true;

		public bool WriteToConsoleAsWell
		{
			get
			{
				return writeToConsoleAsWell;
			}
			set
			{
				writeToConsoleAsWell = value;
			}
		}

		string logFileName = "log.txt";

		public string LogFileName
		{
			get
			{
				return logFileName;
			}
			set
			{
				logFileName = ArgumentValidator.AssertNotNullOrWhiteSpace(value, "value");
			}
		}

		long logFileSizeMaxKB = 1024; /* 1 MB */

		/// <summary>
		/// This value indicates at what size to clear the log and begin a new log file.
		/// Default is 1024 x 1024 (1 MB).
		/// </summary>
		public long LogFileSizeMaxKB
		{
			get
			{
				return logFileSizeMaxKB;
			}
			set
			{
				if (value < 0)
				{
					throw new ArgumentException("Value must be greater than -1.");
				}
				logFileSizeMaxKB = value;
			}
		}

		readonly object fileLock = new object();

		public override Task WriteAsync(LogLevel logLevel,
			string message,
			Exception exception,
			IDictionary<string, object> properties,
			[CallerMemberName]string memberName = null,
			[CallerFilePath] string filePath = null,
			[CallerLineNumber] int lineNumber = 0)
		{
			if (!logLevel.IsGreaterThanOrEqualTo(MinimumLogLevel))
			{
				return TaskUtility.CreateTaskWithResult();
			}

			string logLine = string.Format("<Entry><Time>{0}</Time><LogLevel>{1}</LogLevel><Message>{2}</Message><Member>{3}</Member><File>{4}</File><Line>{5}</Line><Exception>{6}</Exception></Entry>",
								DateTime.UtcNow.ToString(CultureInfo.InvariantCulture),
								logLevel.ToString("G"),
								CleanForXml(memberName),
								CleanForXml(message),
								CleanForXml(filePath),
								lineNumber.ToString(CultureInfo.InvariantCulture),
								CleanForXml(exception));

			ThreadPool.RunAsync(delegate
			{
				if (writeToConsoleAsWell)
				{
					DiagnosticsDebug.WriteLine("LocalStorageLog: " + logLine);
					//Console.WriteLine(logLine);
				}

				lock (fileLock)
				{
					WriteToFile(logLine);
				}
			});

			return TaskUtility.CreateTaskWithResult();
		}

		string CleanForXml(object text)
		{
			if (text == null)
			{
				return string.Empty;
			}

			//			string result = text.ToString().Replace("<", "&lt;").Replace(">", "&gt;");
			string result = WebUtility.HtmlEncode(text.ToString());
			return result;
		}

		/// <summary>
		/// Writes a line to the current log file.
		/// </summary>
		/// <param name="message"></param>
		async void WriteToFile(string message)
		{
			try
			{
				StorageFolder folder = ApplicationData.Current.LocalFolder;
				StorageFile file = await folder.CreateFileAsync(logFileName, CreationCollisionOption.OpenIfExists);

				bool addXmlDeclaration = false;
				long logFileSizeMaxBytes = logFileSizeMaxKB * 1024;
				var props = await file.GetBasicPropertiesAsync();
				if (props.Size >= (decimal)logFileSizeMaxBytes)
				{
					await file.DeleteAsync();
					file = await folder.CreateFileAsync(logFileName, CreationCollisionOption.OpenIfExists);
					addXmlDeclaration = true;
				}
				else if (props.Size < 5)
				{
					addXmlDeclaration = true;
				}

				using (Stream stream = await file.OpenStreamForWriteAsync())
				{
					using (StreamWriter writer = new StreamWriter(stream))
					{
						if (addXmlDeclaration)
						{
							writer.WriteLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
							writer.WriteLine("<Log>");
						}
						writer.WriteLine(message);
					}
				}
			}
			catch (Exception ex)
			{
				DiagnosticsDebug.WriteLine("LocalStorageLog: Unable to write to file. Exception: {0}", ex);
			}
			catch
			{
				DiagnosticsDebug.WriteLine("LocalStorageLog: Unable to write to file.");
			}
		}

		public async Task<string> ReadLog()
		{
			//lock (fileLock)
			//{
				StorageFolder folder = ApplicationData.Current.LocalFolder;
				StorageFile file = await folder.CreateFileAsync(logFileName, CreationCollisionOption.OpenIfExists);
				string fileContent = await FileIO.ReadTextAsync(file);

				if (string.IsNullOrWhiteSpace(fileContent))
				{
					return @"<?xml version=""1.0"" encoding=""ISO-8859-1""?>
						<Log />;";
				}

				return fileContent + "</Log>";
			//}
		}

		public async void Clear()
		{
			StorageFolder folder = ApplicationData.Current.LocalFolder;

			StorageFile file;
			try
			{
				file = await folder.GetFileAsync(logFileName);
			}
			catch (FileNotFoundException) /* Hopefully there will be another way soon. */
			{
				return;
			}

			await file.DeleteAsync();
		}
	}
}